#include "_al_qspi_mod.h"

static void (*sal_qspi_delay_us)(unsigned int us_);
static void (*sal_qspi_set_pin_val_)(unsigned int pin_, unsigned int val_);

void 
sal_qspi_init(
    sal_qspi_info_t* sal_qspi_dev_,
    unsigned long long cs_num,
    // _SAL_QSPI_PIN_LEVEL cs_default_status_, 
    // _SAL_QSPI_PIN_LEVEL clk_defaulte_status_, 
    void(*delay_us_)(unsigned int us_),
    void(*set_pin_val_)(unsigned int pin_, unsigned int val_))
{
    unsigned int i=0;
    // registering delay_us callback
    sal_qspi_delay_us = delay_us_;
    // registering set_pin_val callback
    sal_qspi_set_pin_val_ = set_pin_val_;
    // pin out reset
    for(i=0; i<cs_num; i++){
        sal_qspi_set_pin_val_(sal_qspi_dev_->cs_pins_[i], 1);
    }
    sal_qspi_set_pin_val_(sal_qspi_dev_->clk_pin_, 0);
}

void sal_qspi_wdat_64bit(
    sal_qspi_info_t* sal_qspi_dev_,
    unsigned long long csn_,
    unsigned long long dat_,
    unsigned long long bits_num_
){
    unsigned int i;
    sal_qspi_set_pin_val_(sal_qspi_dev_->cs_pins_[csn_], 0);
    for(i=0; i<bits_num_/4; i++){
        sal_qspi_set_pin_val_(sal_qspi_dev_->dat_pins_[0], (dat_>>(4*i+0))&0x01);
        sal_qspi_set_pin_val_(sal_qspi_dev_->dat_pins_[1], (dat_>>(4*i+1))&0x01);
        sal_qspi_set_pin_val_(sal_qspi_dev_->dat_pins_[2], (dat_>>(4*i+2))&0x01);
        sal_qspi_set_pin_val_(sal_qspi_dev_->dat_pins_[3], (dat_>>(4*i+3))&0x01);
        sal_qspi_set_pin_val_(sal_qspi_dev_->clk_pin_, 1);
        sal_qspi_delay_us(10);
        sal_qspi_set_pin_val_(sal_qspi_dev_->clk_pin_, 0);
        sal_qspi_delay_us(10);
    }
    sal_qspi_set_pin_val_(sal_qspi_dev_->cs_pins_[csn_], 1);
}